//package com.photoeditor.demo.ui.dialog;
//
//
//import android.animation.Animator;
//import android.animation.AnimatorSet;
//import android.animation.ObjectAnimator;
//import android.app.Activity;
//import android.app.Dialog;
//import android.content.Context;
//import android.content.res.Resources;
//import android.graphics.Color;
//import android.graphics.Matrix;
//import android.graphics.drawable.ColorDrawable;
//import android.graphics.drawable.Drawable;
//import android.support.annotation.Nullable;
//import android.text.TextUtils;
//import android.view.LayoutInflater;
//import android.view.View;
//import android.view.ViewGroup;
//import android.view.ViewGroup.LayoutParams;
//import android.view.Window;
//import android.view.WindowManager;
//import android.widget.ImageView;
//import android.widget.ProgressBar;
//import android.widget.RelativeLayout;
//import android.widget.TextView;
//
//import com.bumptech.glide.load.DataSource;
//import com.bumptech.glide.load.engine.GlideException;
//import com.bumptech.glide.request.RequestListener;
//import com.bumptech.glide.request.target.Target;
//import com.common.base.ComponentContext;
//import com.common.base.utils.DeviceUtils;
//import com.common.commercialize.utils.SceneStatisticsNew;
//import com.common.commercialize.utils.TaskRunnable;
//import com.google.android.gms.ads.formats.NativeAdView;
//import com.photoeditor.R;
//import com.photoeditor.demo.ad.AdItemBean;
//import com.photoeditor.demo.ad.AdProvider;
//import com.photoeditor.demo.ad.DownloadAdProvider;
//import com.photoeditor.demo.imageloader.GlideApp;
//import com.photoeditor.demo.model.store.download.DownloadUtils;
//import com.photoeditor.demo.model.store.download.IDownloadListener;
//import com.photoeditor.demo.model.store.module.BaseOnlineManager;
//import com.photoeditor.demo.model.store.module.HomeOnlineManager;
//import com.photoeditor.demo.model.store.module.StoreOnlineBean;
//import com.photoeditor.demo.model.store.module.StoreOnlineManager;
//import com.photoeditor.demo.util.CubicBezierInterpolator;
//import com.photoeditor.demo.util.FontUtil;
//import com.wv.nw.ui.view.BaseNativeAdView;
//
//import org.greenrobot.eventbus.EventBus;
//
//import java.util.ArrayList;
//import java.util.concurrent.CopyOnWriteArraySet;
//
//import static com.photoeditor.demo.model.store.module.BaseOnlineManager.STORE_FUNC_TYPE_UNKNOWN;
//
//
///**
// * 下载页面广告现分两块：
// * 第一块是页面上的大广告
// * 第二块是页面关闭是的插屏广告
// * 策略id为FUN_ID_INAPP_DOWNLOAD_PAGE
// * 广告位id需要配置两个，第一个为页面打广告，第二个为页面退出广告
// * 策略的广告触发时机可以配置back,close，分别为点返回页面关闭和点x关闭 *
// *
// *
// * @author mutour
// */
//public class DownloadAdDialog extends Dialog implements View.OnClickListener {
//
//    public static final String TAG_DOWNLOAD_DIALOG = "download_dialog";
//
//    private Context mContext;
//    private RelativeLayout mAdViewBannerContainer;
//    private ImageView mCloseBtn;
//    private TextView mCompleteText;
//    private TextView mBtnApply;
//    private View mLoadBg;
//    private ProgressBar mProgressBar;
//    private TextView mDown;
//    private View mAdView;
//    private OnActionListener mOnActionListener;
//    private StoreOnlineBean mStoreOnlineBean;
//    private String pkgName;
//    private boolean mClickApply = false;
//    private boolean mClickClose = false;
//    private AdItemBean mAdItemBean;
//    private static boolean mAttachedAd;
//
////    private FullScreenAdProvider mPageCloseAdProvider;
//
//    private static CopyOnWriteArraySet<String> sCurrentShowingNames = new CopyOnWriteArraySet<>();
//
//    private static boolean isShowing = false;
//
//    private static DownloadDialogFragment currentDialog = null;
//
//    private static long lastCallShowTime = 0;
//    private ViewGroup mImageContent;
//
//    public static void show(Activity activity, StoreOnlineBean storeOnlineBean, String adCache, int touchType, OnActionListener listener) {
//        if (sCurrentShowingNames.contains(storeOnlineBean.getName())) {
//            return;
//        }
//
//        if (isShowing) {
//            return;
//        }
//
//        long currentTime = System.currentTimeMillis();
//        if (currentTime - lastCallShowTime < 1000 * 5) {
//            DownloadAdProvider.getInstance().statisticsNoShowAd(AdProvider.REASON_LOCAL_SHOW_TIME_INTERVAL_LIMIT);
//            return;
//        }
//        lastCallShowTime = currentTime;
//
//        try {
//            DownloadDialogFragment downloadDialogFragment = DownloadDialogFragment.newInstance(storeOnlineBean, adCache, touchType);
//            downloadDialogFragment.show(activity.getFragmentManager(), TAG_DOWNLOAD_DIALOG);
//            downloadDialogFragment.setListener(listener);
//
//            if (currentDialog != null) {
//                currentDialog.dismiss();
//            }
//            currentDialog = downloadDialogFragment;
//        } catch (Exception ignored) {
//            DownloadAdProvider.getInstance().statisticsNoShowAd(ignored.getMessage());
//        }
//
//    }
//
//    public static void refreshAd(AdItemBean adItemBean) {
//        if (currentDialog != null) {
//            currentDialog.refreshAd(adItemBean);
//        } else {
//            DownloadAdProvider.getInstance().statisticsNoShowAd(AdProvider.REASON_PAGE_NO_SHOWING);
//        }
//    }
//
//    public static boolean hasDialog() {
//        return currentDialog != null;
//    }
//
//    public static boolean isAttachedAd() {
//        return mAttachedAd;
//    }
//
//    public DownloadAdDialog(Context context, StoreOnlineBean storeOnlineBean, AdItemBean adItemBean) {
//        super(context, R.style.dialog_fullscreen);
//        mContext = context;
//        mStoreOnlineBean = storeOnlineBean;
//        mAdItemBean = adItemBean;
//        View view = LayoutInflater.from(mContext).inflate(R.layout.layout_ad_download_completed, null);
//        mAdViewBannerContainer = (RelativeLayout) view.findViewById(R.id.ad_view_layout);
//        mImageContent = view.findViewById(R.id.image_content);
//        mBtnApply = view.findViewById(R.id.btn_apply);
//        mCloseBtn = (ImageView) view.findViewById(R.id.iv_close);
//        mLoadBg = view.findViewById(R.id.store_download_layout);
//        mDown = (TextView) view.findViewById(R.id.store_download);
//        mProgressBar = (ProgressBar) view.findViewById(R.id.store_progressBar);
//        mCompleteText = view.findViewById(R.id.complete);
//
//        boolean isInstalled = StoreOnlineManager.getInstance().isInstalledByPkgName(storeOnlineBean);
//        if (isInstalled) {
//            /*if(!showApplyBtn()) {
//                mLoadBg.setVisibility(View.GONE);
//                mBtnApply.setVisibility(View.GONE);
//            } else*/ {
//                mBtnApply.setVisibility(View.VISIBLE);
//                mBtnApply.setOnClickListener(DownloadAdDialog.this);
//                mLoadBg.setVisibility(View.GONE);
//            }
//            mCompleteText.setText(R.string.ad_download_completed);
//        } else {
//            startCompleteTextAnimation();
//        }
//
//        int type = HomeOnlineManager.getInstance().getBeanType(storeOnlineBean);
//        if (type == StoreOnlineManager.STORE_FUNC_TYPE_UNKNOWN) {
//            type = StoreOnlineManager.getInstance().getBeanType(storeOnlineBean);
//        }
////        if (type == BaseOnlineManager.STORE_FUNC_TYPE_FILTER) {
////            pkgName = mStoreOnlineBean.getId();
////        } else {
//            pkgName = mStoreOnlineBean.getPkgName();
////        }
//
//        DownloadUtils.getInstance().addListener(downloadListener);
//
//        FontUtil.setCustomFont((TextView) mCompleteText, (TextView) mBtnApply);
//
//        int width = LayoutParams.MATCH_PARENT;
//        int height = LayoutParams.MATCH_PARENT;
//        LayoutParams layoutParams = new LayoutParams(width, height);
//        setContentView(view, layoutParams);
//
//        // 实例化一个ColorDrawable颜色为半透明
//        ColorDrawable dw = new ColorDrawable(Color.TRANSPARENT);
//        //点back键和其他地方使其消失,设置了这个才能触发OnDismisslistener ，设置其他控件变化等操作
//        view.setBackgroundDrawable(dw);
//
//        this.setContentView(view);
//
//        mCloseBtn.setOnClickListener(this);
//
////        if (!SVipManager.getInstance().isSVipUser()) {
////            InappStrategyBean.InappStrategyConfig config = InappAdManager.getInstance().getStrategyConfig(CameraStrategyConstant.FUN_ID_INAPP_DOWNLOAD_PAGE);
////            if (config != null && config.getAdTriggerType() != InappStrategyBean.AdTrigger.NO) {
////                mPageCloseAdProvider = new FullScreenAdProvider("download_dialog", BatmobiConstant.BatmobiAdPlacementID.PLACEMENTID_NATIVE_DOWNLOAD_DIALOG_CLOSE, CameraStrategyConstant.FUN_ID_INAPP_DOWNLOAD_PAGE);
////                // 没有策略或没有触发时机，不展示广告
////                if (mPageCloseAdProvider.needRequest(1)) {
////                    mPageCloseAdProvider.loadAd();
////                }
////            }
////        } else {
////            AdProvider.statisticsNoRequestAd("download_dialog", AdProvider.REASON_SVIP_USER);
////        }
//    }
//
//    private void startCompleteTextAnimation() {
//        TaskRunnable taskRunnable = new TaskRunnable(500, TaskRunnable.TYPE_MAIN) {
//            @Override
//            public void run() {
//                if (DownloadAdDialog.this.isShowing()) {
//                    CharSequence text = mCompleteText.getText();
//                    if (TextUtils.equals(text, "Download")) {
//                        mCompleteText.setText("Download.");
//                    } else if (TextUtils.equals(text, "Download.")) {
//                        mCompleteText.setText("Download..");
//                    } else if (TextUtils.equals(text, "Download..")) {
//                        mCompleteText.setText("Download...");
//                    } else if (TextUtils.equals(text, "Download...")) {
//                        mCompleteText.setText("Download");
//                    } else {
//                        return;
//                    }
//                    this.runSelfAdaptation();
//                }
//            }
//        };
//        taskRunnable.runSelfAdaptation();
//    }
//
//    public void setDownText(String res, int bgResId, int color) {
//        mDown.setText(res);
//        mDown.setTextColor(color);
//        mLoadBg.setBackgroundResource(bgResId);
//        mDown.setCompoundDrawables(null, null, null, null);
//    }
//
//    @Override
//    public void onClick(View v) {
//        if (mCloseBtn == v) {
//            mClickClose = true;
//            dismiss();
//        } else if (mBtnApply == v) {
//            if (mOnActionListener != null) {
//                mClickApply = true;
//                mOnActionListener.onApply();
//                dismiss();
//            }
//        }
//    }
//
//    public void onDismiss() {
//        currentDialog = null;
//        DownloadUtils.getInstance().removeListener(downloadListener);
//        if (mAdItemBean != null) {
//            mAdItemBean.destory();
//            mAdItemBean = null;
//        }
//        sCurrentShowingNames.remove(mStoreOnlineBean.getName());
//        mAdViewBannerContainer.removeAllViews();
//        isShowing = false;
//        mAttachedAd = false;
//        if (mOnActionListener != null) {
//            mOnActionListener.onDismiss(mClickApply, mClickClose);
//        }
//
////        if (mPageCloseAdProvider != null) {
////            InappStrategyBean.InappStrategyConfig config = InappAdManager.getInstance().getStrategyConfig(CameraStrategyConstant.FUN_ID_INAPP_DOWNLOAD_PAGE);
////            String entrance = mClickClose ? "close" : "back";
////            if (config != null) {
////                int adTriggerType = InappStrategyBean.AdTrigger.NO;
////                if (mClickClose) {
////                    adTriggerType = InappStrategyBean.AdTrigger.CLOSE;
////                } else {
////                    adTriggerType = InappStrategyBean.AdTrigger.BACK;
////                }
////                if (!config.meetAdTrigger(adTriggerType)) {
////                    mPageCloseAdProvider.statisticsNoShowAd(AdProvider.REASON_PROTOCOL_UN_FIT);
////                    mPageCloseAdProvider.destroyAd();
////                    return;
////                }
////            }
////            mPageCloseAdProvider.showAd(null, entrance);
////        }
//    }
//
//    public void setOnActionListener(OnActionListener listener) {
//        mOnActionListener = listener;
//    }
//
//    public void setAdCacheKey(AdItemBean adItemBean) {
//        //如果之前有广告，不再刷新，banner广告刷新会导致显示空白
//        View lastView = null;
//        if (mAdViewBannerContainer.getChildCount() > 0) {
//            lastView = mAdViewBannerContainer.getChildAt(0);
//        }
//        if (lastView instanceof BaseNativeAdView || lastView instanceof NativeAdView) {
//            DownloadAdProvider.getInstance().statisticsNoShowAd(AdProvider.REASON_AD_SHOWING);
//            return;
//        }
//        mAdItemBean = adItemBean;
//        showAd();
//    }
//
//    public void showAd() {
//        View lastView = null;
//        if (mAdViewBannerContainer.getChildCount() > 0) {
//            lastView = mAdViewBannerContainer.getChildAt(0);
//        }
//
//        if (/*!SVipManager.getInstance().isSVipUser() &&*/ mAdItemBean != null && mAdItemBean.hasAd() && !mAttachedAd) {
//            mAttachedAd = true;
//            mAdViewBannerContainer.setVisibility(View.VISIBLE);
//
//            if (mAdView == null) {
//                mAdItemBean.setNeedPaddingAdMask(true);
//                mAdView = mAdItemBean.createAdView(R.layout.ad_store_view);
//            }
//
//            mAdViewBannerContainer.addView(mAdView);
//
//            CubicBezierInterpolator cubicBezierInterpolator = new CubicBezierInterpolator(0, 1.06, .73, 1);
//
//            AnimatorSet animatorSet = new AnimatorSet();
//            ObjectAnimator adViewTranslateX = ObjectAnimator.ofFloat(mAdView, "translationX", DeviceUtils.getScreenWidthPx(), 0).setDuration(800);
//            animatorSet.setInterpolator(cubicBezierInterpolator);
//            if (lastView != null) {
//                ObjectAnimator lastViewTranslateX = ObjectAnimator.ofFloat(lastView, "translationX", 0, -DeviceUtils.getScreenWidthPx()).setDuration(800);
//                final View finalLastView = lastView;
//                animatorSet.addListener(new Animator.AnimatorListener() {
//                    @Override
//                    public void onAnimationStart(Animator animation) {
//
//                    }
//
//                    @Override
//                    public void onAnimationEnd(Animator animation) {
//                        mAdViewBannerContainer.removeView(finalLastView);
//                    }
//
//                    @Override
//                    public void onAnimationCancel(Animator animation) {
//
//                    }
//
//                    @Override
//                    public void onAnimationRepeat(Animator animation) {
//
//                    }
//                });
//                animatorSet.playTogether(adViewTranslateX, lastViewTranslateX);
//            } else {
//                animatorSet.play(adViewTranslateX);
//            }
//            animatorSet.start();
//        } else {
//            /*if (SVipManager.getInstance().isSVipUser()) {
//                DownloadAdProvider.getInstance().statisticsNoShowAd(AdProvider.REASON_SVIP_USER);
//            } else */if (mAdItemBean == null || !mAdItemBean.hasAd()) {
//                DownloadAdProvider.getInstance().statisticsNoShowAd(AdProvider.REASON_NO_VALID_AD);
//            } else if (mAttachedAd) {
//                DownloadAdProvider.getInstance().statisticsNoShowAd(AdProvider.REASON_AD_SHOWING);
//            }
//            mAttachedAd = false;
//            mAdViewBannerContainer.removeAllViews();
//
//            final ImageView imageView = new ImageView(mContext);
//
//            String banner = "";
//            int beanType = HomeOnlineManager.getInstance().getBeanType(mStoreOnlineBean);
//            if (beanType == STORE_FUNC_TYPE_UNKNOWN) {
//                beanType = StoreOnlineManager.getInstance().getBeanType(mStoreOnlineBean);
//            }
//            if (TextUtils.isEmpty(mStoreOnlineBean.getBanner())) {
//                ArrayList<StoreOnlineBean> childModules = mStoreOnlineBean.getChildModules();
//                if (childModules != null && childModules.size() > 0) {
//                    StoreOnlineBean storeOnlineBean = childModules.get(0);
//                    if (storeOnlineBean != null) {
////                        if (beanType == BaseOnlineManager.STORE_FUNC_TYPE_STICKER) {
////                            banner = storeOnlineBean.getPreview();
////                        } else {
//                            banner = storeOnlineBean.getBanner();
////                        }
//                    }
//                }
//            } else {
////                if (beanType == BaseOnlineManager.STORE_FUNC_TYPE_STICKER) {
////                    banner = mStoreOnlineBean.getPreview();
////                } else {
//                    banner = mStoreOnlineBean.getBanner();
////                }
//            }
//            GlideApp.with(ComponentContext.getContext())
//                    .load(banner)
//                    .placeholder(R.drawable.ic_default_image)
//                    .listener(new RequestListener<Drawable>() {
//                        @Override
//                        public boolean onLoadFailed(@Nullable GlideException e, Object o, Target<Drawable> target, boolean b) {
//                            return false;
//                        }
//
//                        @Override
//                        public boolean onResourceReady(Drawable drawable, Object o, Target<Drawable> target, DataSource dataSource, boolean b) {
//                            int minWidth = mImageContent.getWidth();
//                            int height = drawable.getIntrinsicHeight();
//                            int width = drawable.getIntrinsicWidth();
//                            if (height < minWidth || width < minWidth) {
//                                float scale = Math.max((float) (minWidth) / height, (float) (minWidth) / width);
//                                Matrix matrix = new Matrix();
//                                matrix.setScale(scale, scale);
//                                ((ImageView) imageView).setImageMatrix(matrix);
//                            }
//                            return false;
//                        }
//                    })
//                    .into(imageView);
//            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
//            imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
////            int dialogW = DeviceUtils.getScreenWidthPx(mContext) - DeviceUtils.dip2px(mContext, 40);
////            lp.width = dialogW;
//            // 按图片比例等比算出高度
////            lp.height = (dialogW - DeviceUtils.dip2px(mContext, 15) * 2) * 300 / 614; // 图片宽高比：  614 / 300
//            mAdViewBannerContainer.addView(mImageContent);
//            mImageContent.addView(imageView, lp);
//        }
//    }
//
//    @Override
//    public void show() {
//        if (!isShowing()) {
//            showAd();
//        }
//        super.show();
//
//        Window window = getWindow();
//        if (window != null) {
//            View decorView = window.getDecorView();
//            if (decorView != null) {
//                decorView.setPadding(0, 0, 0, 0);
//            }
//            WindowManager.LayoutParams lp = window.getAttributes();
//            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
//            lp.height = WindowManager.LayoutParams.MATCH_PARENT;
//            window.setAttributes(lp);
//        }
//        sCurrentShowingNames.add(mStoreOnlineBean.getName());
//        isShowing = true;
//    }
//
//    public static void statistics(String eventSuffix, String... attributes) {
//        SceneStatisticsNew.statistics("download" + eventSuffix, attributes);
//    }
//
//    IDownloadListener downloadListener = new IDownloadListener() {
//        @Override
//        public String getDownloadId() {
//            return pkgName;
//        }
//
//        @Override
//        public void onProgressUpdate(String downloadId, int percentage) {
//            if (mDown == null || mProgressBar == null) {
//                return;
//            }
//            Resources res = getContext().getResources();
//            String percentageStr;
//            if (percentage <= 0) {
//                // 开始下载初始化
//                mProgressBar.setProgress(percentage);
//                percentageStr = percentage + "%";
//                setDownText(percentageStr, R.drawable.goods_download_btn, res.getColor(R.color.primary_color));
//            } else if (percentage >= 0 && percentage < 100) {
//                // 下载中
//                percentageStr = percentage + "%";
//                mProgressBar.setProgress(percentage);
//                setDownText(percentageStr, R.drawable.goods_download_btn, res.getColor(R.color.primary_color));
//            } else if (percentage >= 100) {
//                // 下载完成
//                mProgressBar.setProgress(100);
//
//                /*if(InappAdManager.getInstance().isBuyUser()) {
//                    if (DownloadAdDialog.this.isShowing()) {
//                        mBtnApply.setVisibility(View.GONE);
//                        mLoadBg.setVisibility(View.GONE);
//                        mCompleteText.setText(R.string.ad_download_completed);
//                    }
//                } else */
//                {
//                    CubicBezierInterpolator cubicBezierInterpolator = new CubicBezierInterpolator(0, 1.06, .73, 1);
//                    ObjectAnimator viewScaleX = ObjectAnimator.ofFloat(mLoadBg, "ScaleX", 1f, 0.7f);
//                    ObjectAnimator viewTranslateX = ObjectAnimator.ofFloat(mLoadBg, "translationX", 0, DeviceUtils.dip2px(156) * 0.15f);
//                    ObjectAnimator textAlpha = ObjectAnimator.ofFloat(mDown, "Alpha", 1f, 0f);
//                    AnimatorSet animatorSet = new AnimatorSet().setDuration(300);
//
//                    animatorSet.addListener(new Animator.AnimatorListener() {
//                        @Override
//                        public void onAnimationStart(Animator animation) {
//
//                        }
//
//                        @Override
//                        public void onAnimationEnd(Animator animation) {
//                            if (DownloadAdDialog.this.isShowing()) {
////                                    setDownText(getContext().getResources().getString(R.string.ad_apply), R.drawable.goods_download_progress_selector, Color.WHITE);
//                                mBtnApply.setVisibility(View.VISIBLE);
//                                mBtnApply.setOnClickListener(DownloadAdDialog.this);
//                                mCompleteText.setText(R.string.ad_download_completed);
//                                mLoadBg.setVisibility(View.GONE);
//                            }
//                        }
//
//                        @Override
//                        public void onAnimationCancel(Animator animation) {
//
//                        }
//
//                        @Override
//                        public void onAnimationRepeat(Animator animation) {
//
//                        }
//                    });
//                    animatorSet.setInterpolator(cubicBezierInterpolator);
//                    animatorSet.playTogether(viewScaleX, viewTranslateX, textAlpha);
//                    animatorSet.start();
//                }
//            }
//        }
//
//        @Override
//        public void onFailed(String packageName) {
//
//        }
//
//        @Override
//        public String getFullActivityName() {
//            return null;
//        }
//    };
//
//    public interface OnActionListener {
//        void onDismiss(boolean clickApply, boolean clickClose);
//
//        void onApply();
//    }
//}
